package jude.java.money.ant;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.BuildException;

import sun.misc.BASE64Decoder;

public class Encoder extends Base {
	
	private String source;
	private String type;
	private String property;
	
	public void setSource(String source) {
		this.source = source;
	}
	
	public void setType(String type) {
		this.type = isEmpty(type) ? null : type.toLowerCase();
	}
	
	public void setProperty(String property) {
		this.property = isEmpty(property) ? null : property;
	}
	
	@Override
	public void execute() throws BuildException {
		if (property == null || type == null)
			return;
		if (source == null) {
			source = getProject().getProperty(property);
			if (source == null)
				return;
		}
		String r = source;
		if ("md5".equals(type)) {
			r = getMD5(source);
		} else if ("base64".equals(type)) {
			r = getBase64Encoder(source);
		} else if ("base64d".equals(type)) {
			r = getBase64Decoder(source);
		}
		getProject().setProperty(property, r);
	}

	public static String getMD5(InputStream in) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			byte[] buffer = new byte[8192];
			int read = 0;
			while ((read = in.read(buffer)) > 0) {
				digest.update(buffer, 0, read);
			}
			byte[] md5sum = digest.digest();
			BigInteger bigInt = new BigInteger(1, md5sum);
			return StringUtils.leftPad(bigInt.toString(16), 32, '0');
		} catch (Throwable e) {
			return null;
		}
	}
	
    /** 获取字符串的MD5值(32位, 小写) */
	public static String getMD5(String content) {
		try {
			if (content == null)
				content = "";
			InputStream in = new ByteArrayInputStream(content.getBytes());
			return getMD5(in);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}
	
	// 将 s 进行 BASE64 编码
	public static String getBase64Encoder(String s) {
		if (s == null)
			return null;
		return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
	}

	// 将 BASE64 编码的字符串 s 进行解码
	public static String getBase64Decoder(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(s);
			return new String(b, "UTF-8");
		} catch (Exception e) {
			return null;
		}
	}
	
	public static void main(String[] args) {
		Encoder e = new Encoder();
		e.setType("md5");
		e.setSource("Jude");
		String c = Encoder.getBase64Encoder("Judejudejudezhuliren");
		System.out.println(c);
		System.out.println(Encoder.getBase64Decoder(c));
		System.out.println(Encoder.getMD5("Judejudejudezhuliren"));
	}
}
